<?php
namespace Common\Models;
use Common\BaseModel;
use Common\Common;

class BShopGoods extends BaseModel
{
    public $res;
    public $expire;
    public $columns;
    public function initialize()
    {
        parent::initialize();
        $this->setSource('b_shop_goods');
        $this->columns = 'g.goods_sn as GoodsId,g.name as Title,g.name as ShortTitle,g.detailed_img as PicLogo,(sku.price-sku.endprice) as CouponMoney,sku.price as Price,sku.endprice as EndPrice,g.goods_commit as MonthSale,sku.commission AS Commission,"self" as Site,info.shop_name as ShopName,"self" as Site,"自购" as ShopType';
    }


    /**
     * 根据店铺id获取店铺商品和店铺的基本信息
     */
    public function get_goods_list($shop_id)
    {
        $conditions = "g.status=1 AND g.admin_status=1 AND g.shop_id={$shop_id} AND sku.is_default=1";
        $order_by = "sku.commission DESC";
        $sql = <<<EFO
SELECT {$this->columns} from b_shop_goods as g
LEFT JOIN b_shop_goods_sku as sku on sku.goods_id=g.id
LEFT JOIN b_shop_users_info as info on info.shop_id=g.shop_id
WHERE $conditions ORDER BY $order_by LIMIT 10
EFO;
        $get_list = $this->getDI()->get('dbMaster')->fetchAll($sql);
        return $get_list;
    }




    public function shop_goods_list($params=[])
    {
        $page = $params['page'] <= 1 ? 0 : ($params['page'] - 1) * $params['page_size'];
        $page_size = $params['page_size'];
        $conditions = "g.status=1 AND g.admin_status=1 AND g.shop_id={$params['shop_id']} AND sku.is_default=1";
        $order_by = "sku.commission DESC";
        if ((isset($params['order_by']) || !empty($params['order_by'])) && (isset($params['sort']) || !empty(isset($params['sort'])))) {
            //$order_by = "{$params['order_by']} {$params['sort']}";
        }
        $sql = <<<EFO
SELECT {$this->columns} from b_shop_goods as g
LEFT JOIN b_shop_goods_sku as sku on sku.goods_id=g.id
LEFT JOIN b_shop_users_info as info on info.shop_id=g.shop_id
WHERE $conditions ORDER BY $order_by LIMIT $page,$page_size
EFO;
        $get_list = $this->getDI()->get('dbMaster')->fetchAll($sql);
        return $get_list;
    }


    /**
     * 获取用户信息
     */
    public function get_user_shop($params=[]){
        $page = $params['page'] ? intval($params['page']) : 1;
        $size = $params['page_size'] ? intval($params['page_size']) : 10;
        if ($page > 0) {
            $page = ($page - 1) * $size;
        }
        $conditions="s.id>0";
        if(isset($params['shop_id']) && !empty($params['shop_id'])){
            $conditions .=" AND s.id={$params['shop_id']}";
        }
        $sql=<<<EFO
        SELECT g.*,s.name as shop_name,s.username
        FROM b_shop_goods as g
        LEFT JOIN b_shop_users as s on s.id=g.shop_id
        WHERE $conditions ORDER BY s.created_at desc LIMIT $page,$size 
EFO;
        $get_list['items'] = $this->getDI()->get('dbMaster')->fetchAll($sql);
        $get_list['total'] = $this->count(['column'=>'id']);
        return $get_list;
    }


    /**
     * 获取首页商品数据
     */
    public function get_goods_index($params=[]){
        $page = $params['page'] ? intval($params['page']) : 1;
        $size = $params['page_size'] ? intval($params['page_size']) : 10;
        if ($page > 0) {
            $page = ($page - 1) * $size;
        }
        $conditions = "g.status=1 AND g.admin_status=1 AND sku.is_default=1";
        if(isset($params['category_id']) && empty($page['category_id'])){
            $conditions .= " AND g.category_id='{$params['category_id']}'";
        }
        $sql=<<<EFO
SELECT {$this->columns} from b_shop_goods as g
LEFT JOIN b_shop_goods_sku as sku on sku.goods_id=g.id
LEFT JOIN b_shop_users_info as info on info.shop_id=g.shop_id
WHERE $conditions LIMIT $page,$size
EFO;
        $get_list = $this->getDI()->get('dbMaster')->fetchAll($sql);
        return $get_list;
    }



    /**
     * 根据商品的商品号获取商品信息
     */
    public function get_goods_sn($params=[]){
        $conditions = "g.goods_sn='{$params['goods_id']}'";
        $columns='g.id,g.goods_sn as GoodsId,g.name as Title,g.banner,g.shop_id as ShopId,info.shop_avatar as ShopIcon,g.details as Details,g.name as ShortTitle,g.describe as Suggest,g.detailed_img as PicLogo,(sku.price-sku.endprice) as CouponMoney,sku.price as Price,sku.stock as Stock,sku.endprice as EndPrice,g.goods_commit as MonthSale,sku.commission AS Commission,"self" as Site,info.shop_name as ShopName,"self" as Site,"自购" as ShopType';
        $sql=<<<EFO
SELECT {$columns} from b_shop_goods as g
LEFT JOIN b_shop_goods_sku as sku on sku.goods_id=g.id
LEFT JOIN b_shop_users_info as info on info.shop_id=g.shop_id
WHERE $conditions
EFO;
        $get_list = $this->getDI()->get('dbMaster')->fetchOne($sql);
        if(!$get_list){
            return [];
        }else{
            $get_list['SmallImages'] = $get_list['banner'] ? explode(',',$get_list['banner']) : [];
            $get_list['PicList'] = $get_list['banner'] ? explode(',',$get_list['banner']) : [];
            $get_list['CouponStartTime'] = date('Y-m-d',mktime(0, 0, 0, date('m'), date('d') - 6, date('Y')));
            $get_list['CouponEndTime'] = date('Y-m-d',strtotime(date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y")))));
            $get_list['ShopUrl'] = "";
            $get_list['DescTxt'] = "4.90";
            $get_list['ServTxt'] = "4.90";
            $get_list['AvgTxt'] = "4.90";
            $FCollectDb = new Collects();
            $goods_ids = "'{$params['goods_id']}'";
            $get_collect = $FCollectDb->find_by_ids($params['user_id'],$goods_ids);
            $get_list['IsColletc']=$get_collect ? true : false;

            $BShopGoodsSkuDb = new BShopGoodsSku();
            $sku_arr = $BShopGoodsSkuDb->find(array(
                'conditions'=>"goods_id={$get_list['id']}"
            ))->toarray();
            if(!$sku_arr){
                $get_list['Sku'] = $sku_arr;
            }else{
                $sku_key_arr = array_unique(explode('_',implode('_',array_column($sku_arr,'value_ids'))));
                $sku_key_ids = implode(',',$sku_key_arr);

                $BShopSkuValueDb = new BShopSkuValue();
                $get_key_arr = $BShopSkuValueDb->find(array(
                    'conditions'=>"id in($sku_key_ids)",
                    'columns'=>"key_id",
                    'group'=>'key_id',
                ))->toarray();
                $BShopSkuKeyDb = new BShopSkuKey();
                $sku_key=[];
                foreach($get_key_arr as $key=>$value){
                    $sku_key[$key] = $BShopSkuKeyDb->findFirst(array(
                        'conditions'=>"id={$value['key_id']}",
                        'columns'=>'id,key_name'
                    ))->toarray();
                    $sku_key[$key]['child'] = $BShopSkuValueDb->find(array(
                        'conditions'=>"key_id={$value['key_id']} AND id in($sku_key_ids)",
                        'columns'=>'id,key_id,value_name'
                    ))->toarray();
                }
                $get_list['all_sku_value'] = $sku_key;

                foreach($sku_arr as $key=>$value){
                    $sku_arr[$key]['value_ids_name'] = $BShopSkuValueDb->getValueName($value['value_ids']);
                }
                $get_list['Sku'] = $sku_arr;
            }
            return $get_list;
        }
    }


    /**
     * 商品是否下架和商品是否存在
     */
    public function find_goods_sn($goods_sn){
        $get_one = $this->findFirst(array(
            "conditions"=>"admin_status=1 AND status=1 AND goods_sn='{$goods_sn}'"
        ));
        return $get_one;
    }


    /**
     * 统计用户提交过来的金额
     */
    public function all_submit_price($items){
        $all_money = 0;
        $BShopGoodsSkuDb = new BShopGoodsSku();
        foreach($items as $key=>$value){
            if(isset($value['sku_id']) && !empty($value['sku_id'])){
                $b_shop_goods = $BShopGoodsSkuDb->findFirstById($value['sku_id']);
                if(!$b_shop_goods){
                    continue;
                }
                $items_price = $value['num'] * $b_shop_goods->endprice;
                $all_money = Common::bc($all_money,$items_price,'+',2);
            }else{
                $shop_goods = $this->findFirstByGoodsSn($value['goods_id']);
                if(!$shop_goods){
                    continue;
                }
                $items_price = $value['num'] * $shop_goods->discount_price;
                $all_money = Common::bc($all_money,$items_price,'+',2);
            }
        }
        return $all_money;
    }


}
